package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.dto.DishDto;
import com.itheima.dto.SetmealDto;
import com.itheima.entity.*;
import com.itheima.service.CategoryService;
import com.itheima.service.DishService;
import com.itheima.service.SetmealDishService;
import com.itheima.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RequestMapping("/setmeal")
@RestController
public class SetmealController {
    @Autowired
    private SetmealService setmealService;
    @Autowired
    private SetmealDishService setmealDishService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private DishService dishService;

    /**
     * 新增套餐
     * @param setmealDto
     * @return
     */
    //清除缓存
    @CacheEvict(value = "setmeal",key = "#setmealDto.categoryId +'::1'")
    @PostMapping
    public R save (@RequestBody SetmealDto setmealDto){
        log.info("要录入的套餐信息为：{}",setmealDto);
        setmealService.saveWithDish(setmealDto);
        return R.success("新增套餐成功");
    }

    /**
     * 分页
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R page(Integer page, Integer pageSize , String name){
        log.info("page:{},pageSize:{},name:{}",page,pageSize,name);

        //构建分页构造器
        Page<Setmeal> setmealPage = new Page<>(page,pageSize);
        LambdaQueryWrapper<Setmeal> slqw = new LambdaQueryWrapper<>();
        //进行模糊查询
        slqw.like(name != null,Setmeal::getName,name);
        //按更新时间排序
        slqw.orderByDesc(Setmeal::getUpdateTime);
        //完成初步排序
        setmealService.page(setmealPage,slqw);

        Page<SetmealDto> setmealDtoPage = new Page<>();
        //分页的基本信息进行传输，除了records
        BeanUtils.copyProperties(setmealPage,setmealDtoPage,"records");

        List<Setmeal> records = setmealPage.getRecords();

        List<SetmealDto> setmealDtoList = records.stream().map(item -> {
            SetmealDto setmealDto = new SetmealDto();
            BeanUtils.copyProperties(item, setmealDto);

            Long categoryId = item.getCategoryId();
            Category category = categoryService.getById(categoryId);

            if (category != null) {
                String categoryName = category.getName();
                setmealDto.setCategoryName(categoryName);
            }

            return setmealDto;
        }).collect(Collectors.toList());

        setmealDtoPage.setRecords(setmealDtoList);

        return R.success(setmealDtoPage);
    }

    /**
     * 多id删除
     * @param ids
     * @return
     */
    //只要删除，就会清空所有缓存
    @CacheEvict(value = "setmeal",allEntries = true)
    @DeleteMapping
    public R delete(@RequestParam List<Long> ids){
        log.info("ids:{}",ids);

        setmealService.deleteWithDish(ids);

        return R.success("套餐数据删除成功");
    }

    /**
     * 批量停售/起售
     * @param status
     * @param ids
     * @return
     */
    @PostMapping("/status/{status}")
    public R status(@PathVariable Integer status , @RequestParam List<Long> ids){
        log.info("ids为:{}",ids);
        log.info("status为:{}",status);

        setmealService.statusWithDish(status,ids);

        return R.success("修改成功");
    }

    /**
     * 修改套餐，先映射信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R getthing(@PathVariable Long id){
        log.info("要查询的id为{}",id);

        SetmealDto setmealDto = new SetmealDto();

        Setmeal setmeal = setmealService.getById(id);
        BeanUtils.copyProperties(setmeal,setmealDto);

        Category category = categoryService.getById(setmeal.getCategoryId());
        String categoryName = category.getName();
        setmealDto.setCategoryName(categoryName);

        LambdaQueryWrapper<SetmealDish> lqw = new LambdaQueryWrapper<>();
        lqw.eq(SetmealDish::getSetmealId,setmeal.getId());
        List<SetmealDish> setmealDishes = setmealDishService.list(lqw);
        setmealDto.setSetmealDishes(setmealDishes);

        log.info("我是数据：{}",setmealDto);

        return R.success(setmealDto);
    }

    /**
     * 修改套餐信息
     * @param setmealDto
     * @return
     */
    @PutMapping
    public R update(@RequestBody SetmealDto setmealDto){
        log.info("要修改的信息为: {}",setmealDto);
        setmealService.updateWithDish(setmealDto);
        return R.success("修改成功");
    }

    /**
     * 根据分类查询启用的套餐
     * @param setmeal
     * @return
     */
    //K = setmeal :: xxx :: 1
    //unless: f返回值中的data数学== null 不添加，不等于null添加
    @Cacheable(value = "setmeal",key = "#setmeal.categoryId +'::'+ #setmeal.status",unless = "#result.data == null")
    @GetMapping("/list")
    public R list(Setmeal setmeal){
        //接收参数
        log.info("Setmal :{}",setmeal);
        //构造条件
        LambdaQueryWrapper<Setmeal> lqw = new LambdaQueryWrapper<>();
        lqw.eq(setmeal.getCategoryId() != null,Setmeal::getCategoryId,setmeal.getCategoryId());
        lqw.eq(setmeal.getStatus() != null,Setmeal::getStatus,setmeal.getStatus());

        //查询
        List<Setmeal> setmealList = setmealService.list(lqw);

        //返回数据
        return R.success(setmealList);
    }

    /**
     * 具体信息查看
     * @param id
     * @return
     */
    @GetMapping("/dish/{id}")
    public R dish(@PathVariable Long id){
        //接收参数
        log.info("id为：{}",id);

        //构造查询条件
        LambdaQueryWrapper<SetmealDish> lqw = new LambdaQueryWrapper<>();
        lqw.eq(id != null,SetmealDish::getSetmealId,id);
        //查询
        List<SetmealDish> dishList = setmealDishService.list(lqw);

        //套餐的图片条件问题
        dishList = dishList.stream().map(item -> {
            //同菜品id去查询菜品图片信息
            Dish dish = dishService.getById(item.getDishId());
            String image = dish.getImage();
            item.setImage(image);
            return item;
        }).collect(Collectors.toList());

        //返回数据
        return R.success(dishList);
    }
}
